package it.lapomuge.score.android;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.bluetooth.BluetoothSocket;
import android.widget.TextView;

public class ConnectedDevice {

	private final BluetoothSocket mmSocket;
	private InputStream mmInStream;
	private OutputStream mmOutStream;
	private TextView out;
	private String codiceConnessione;
	private static int BUFF_LENGHT = 255;

	public ConnectedDevice(BluetoothSocket socket) {
		mmSocket = socket;

		// Get the input and output streams, using temp objects because
		// member streams are final
		try {
			mmInStream = socket.getInputStream();
			mmOutStream = socket.getOutputStream();
		} catch (IOException e) {

		}
	}

	public boolean login(String nome, String pwd) throws IOException {

		String code = "login;" + nome + ";" + pwd;
		send(code);
		String risp = readLine();

		if (risp.equals("nologin") || risp.equals("noconn")) {
			return false;
		} else {
			this.codiceConnessione = risp;
			return true;
		}

	}

	/* Call this from the main activity to shutdown the connection */
	public void cancel() {
		try {
			mmSocket.close();
		} catch (IOException e) {
		}
	}

	public void setOutpunt(TextView t) {
		this.out = t;
	}

	public String readLine() {

		byte[] buf = new byte[BUFF_LENGHT];
		try {
			mmInStream.read(buf);
			String linea = "";
			for (int i = 0; i < buf.length; i++) {
				linea += (char) buf[i];
			}
			return linea.trim();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public void send(String line) {
		try {
			mmOutStream.write(line.getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String nextAtleta() {
		send("next;" + codiceConnessione);
		String next = readLine();
		if (next.startsWith("nonext")) {
			return null;
		} else {
			return next.split(";")[2];
		}

	}

	public boolean vota(int intero, int decimale) {
		send("voto;" + codiceConnessione + ";" + intero + "." + decimale);
		String next = readLine();
		return next.equals("ok");
	}

}
